package com.caiheng.api.service.platfom.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.platform.MapAreaMapper;
import com.caiheng.api.entity.platform.MapArea;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.platfom.MapAreaService;
import com.caiheng.api.util.positionjudge.IsPtInPoly;
import com.caiheng.api.util.positionjudge.Point2D;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 地图区域管理Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-18
 */
@Service
public class MapAreaServiceImpl extends BaseServiceImpl<MapAreaMapper, MapArea> implements MapAreaService {

    @Resource
    private MapAreaMapper mapAreaMapper;

    @Override
    public boolean judge(Point2D point2D, JSONArray jsonArray) {
        JSONObject jsonObject;
        List<Point2D> list = new ArrayList<>();
        Point2D aa;
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonObject = JSONUtil.parseObj(jsonArray.get(i));
            aa = new Point2D(new BigDecimal(jsonObject.get("lng").toString()),
                    new BigDecimal(jsonObject.get("lat").toString()));
            list.add(aa);
        }
        return IsPtInPoly.isPtInPoly(point2D, list);
    }

    @Override
    public boolean isInArea(BigDecimal lng, BigDecimal lat, int areaType) {
        boolean bl = false;
        Point2D point2D = new Point2D(lng,lat);
        QueryWrapper<MapArea> qw = new QueryWrapper<>();
        qw.eq("area_type",areaType);
        List<MapArea> mapAreas = mapAreaMapper.selectList(qw);
        for (MapArea mapArea : mapAreas){
            if (StrUtil.isNotEmpty(mapArea.getPoints())) {
                bl = judge(point2D, JSONUtil.parseArray(mapArea.getPoints()));
                if(bl){
                    return bl;
                }
            }
        }
        return false;
    }
}
